// JavaScript Document
	db// create database
	var db = window.openDatabase('Calendar', '0.1', 'AceCalendar', 200000);
	// create table
	db.transaction(function (tx) {
  		tx.executeSql('CREATE TABLE IF NOT EXISTS EVENTS (id integer, date NUMERIC, logTitle, log, PRIMARY KEY (id))');
	});
	// Wait for device API libraries to load
	//
	$(document).ready(onLoad);
	function onLoad() {
		var year = getURLQueryString("y"), month = getURLQueryString("m");
		var date;
		if(year != "")
			date = new Date(year,month,1);
		else{
				date = new Date();
				date.setDate(1);
		}
		listTheDaysOfMonth(date.getFullYear(), date.getMonth());
		listEventsOfMonth(date.getFullYear(), date.getMonth());
		
		//點擊dayWidget 新增日記
		$(".dayWidget").click(function(){
				var str = $(this).children(".dayContent").first().attr('id');
				str = str.match("[0-9]+");
				if(str == null)
					return;
				str = String.format("?y={0}&m={1}&d={2}&s=index2.html",date.getFullYear(),date.getMonth(),str)
				window.location.href = "eventDetail.html" + str;
			});
		$("#MonthEventList").swipe({
  			swipeRight:function(event, direction, distance, duration, fingerCount) {
					$("body").pagecontainer("change", "index.html", { showLoadMsg: true, transition: 'slide', role:'page',reverse:true}); 
		}});
	}

	//List all days of one Month
	function listTheDaysOfMonth(year,month){
		var date = new Date(year,month,1);				
		$("#lbListMonth").html(date.getFullYear()+". "+ String.padLeft((date.getMonth()+1),2));
		var preMonth =  new Date(year, month-1 ,1);
		$("#preMonth").attr("href","?y=" + preMonth.getFullYear() + "&m=" + preMonth.getMonth());
		var nextMonth = new Date(year, month+1 ,1);
		$("#nextMonth").attr("href","?y=" + nextMonth.getFullYear() + "&m=" +  nextMonth.getMonth());
		//<div class="flex-box">
		//<div class="dayWidget">1<div id="widget-Events1" class="dayContent"><ul><li>上課通知</li></ul></div></div>
		date.setDate(date.getDate() - date.getDay());		//取得當週的第一天的日期
		var widget = '<div class="flex-box">';
		do{
			if(date.getMonth() == month){
				widget += String.format('<div class="monthDayWidget">{0}<div id="monthWidget-Events{1}" class="monthWidgetContent"></div></div>',
				date.getDate(),date.getDate());	
			}else{
				widget += String.format('<div class="monthDayWidget">{0}<div id="monthWidget-Events{1}" class="monthWidgetContent"></div></div>');
			}
			date.setDate(date.getDate()+1);
		}while(month == date.getMonth() || date.getDay() != 0);
		widget += '</div>';
		$("#monthContent").append(widget);
	}

	//List the Events of the Month
	function listEventsOfMonth(year,month)
	{
		//查詢字串設定：2014-07-01
		var date = new Date(year,month,1);
		var strStart = String.format("{0}-{1}-01", date.getFullYear(), String.padLeft((date.getMonth()+1),2));
		var nextMonth = new Date(year, month+1 ,1)
		var strEnd = String.format("{0}-{1}-01", nextMonth.getFullYear(), String.padLeft((nextMonth.getMonth()+1),2));
		
		var ltEvents = [];
		db.transaction( function(tx) {
			//SELECT * FROM EVENTS WHERE date(date) >= date("2014-07-01") and date(date) < date("2014-08-01")
			tx.executeSql('SELECT * FROM EVENTS WHERE date(date) >= date(?) and date(date) < date(?)',
			[strStart,strEnd], function(tx,results) {
					for	(i=0;i<results.rows.length;i++)
					{
						var row = results.rows.item(i);
						m_date = new Date(row['date']);
						if(!ltEvents[m_date.getDate()])
								ltEvents[m_date.getDate()]=[];
						ltEvents[m_date.getDate()].push({ 'id' : row['id'], 'date' :new Date(row['date']),
									  'logTitle' : row['logTitle'], 'log' : row['log']});
					}
				});
		},
		//error callback
		function() {}, 
		//success callback
		function() {
				showEventLogs(ltEvents);
			});
	}
	//showEventLogs in Widget
	function showEventLogs(eventsList){
		i=1;
		while(i < eventsList.length){
			if(eventsList[i]){
				//<ul><li>上午開會</li></ul>
				var strhtml = "<ul>";
				for(var j=0; j < 4 ; j++){
					if(eventsList[i][j]){
						m_date = eventsList[i][j].date;
						strhtml += String.format('<li><a data-ajax="false" style="color:white;" href="eventDetail.html?id={0}">{1}</a></li>',
						 eventsList[i][j].id, eventsList[i][j].logTitle);
					}else{
						strhtml += ""
					}
				}
				strhtml += "</ul>";
				//alert(strhtml);
				$("#monthWidget-Events" + eventsList[i][0].date.getDate()).html(strhtml);
			}
			i++;
		}
		
	}
